package com.ruoyi.manage.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.manage.mapper.CrApplicationMapper;
import com.ruoyi.manage.domain.CrApplication;
import com.ruoyi.manage.domain.CrRecruitment;
import com.ruoyi.manage.service.ICrApplicationService;
import com.ruoyi.manage.service.ICrRecruitmentService;

/**
 * 学生申请Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@Service
public class CrApplicationServiceImpl implements ICrApplicationService 
{
    @Autowired
    private CrApplicationMapper crApplicationMapper;

    @Autowired
    private ICrRecruitmentService crRecruitmentService;

    /**
     * 查询学生申请
     * 
     * @param applicationId 学生申请主键
     * @return 学生申请
     */
    @Override
    public CrApplication selectCrApplicationByApplicationId(Long applicationId)
    {
        return crApplicationMapper.selectCrApplicationByApplicationId(applicationId);
    }

    /**
     * 查询学生申请列表
     * 
     * @param crApplication 学生申请
     * @return 学生申请
     */
    @Override
    public List<CrApplication> selectCrApplicationList(CrApplication crApplication)
    {
        return crApplicationMapper.selectCrApplicationList(crApplication);
    }

    /**
     * 新增学生申请
     * 
     * @param crApplication 学生申请
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCrApplication(CrApplication crApplication)
    {
        crApplication.setCreateTime(DateUtils.getNowDate());
        return crApplicationMapper.insertCrApplication(crApplication);
    }

    /**
     * 修改学生申请
     * 
     * @param crApplication 学生申请
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCrApplication(CrApplication crApplication)
    {
        crApplication.setUpdateTime(DateUtils.getNowDate());
        return crApplicationMapper.updateCrApplication(crApplication);
    }

    /**
     * 批量删除学生申请
     * 
     * @param applicationIds 需要删除的学生申请主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCrApplicationByApplicationIds(Long[] applicationIds)
    {
        return crApplicationMapper.deleteCrApplicationByApplicationIds(applicationIds);
    }

    /**
     * 删除学生申请信息
     * 
     * @param applicationId 学生申请主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCrApplicationByApplicationId(Long applicationId)
    {
        return crApplicationMapper.deleteCrApplicationByApplicationId(applicationId);
    }

    /**
     * 根据学生ID查询申请列表
     * 
     * @param studentId 学生ID
     * @return 申请列表
     */
    @Override
    public List<CrApplication> selectApplicationsByStudentId(Long studentId)
    {
        return crApplicationMapper.selectStudentApplicationList(studentId);
    }

    /**
     * 根据社团ID查询申请列表
     * 
     * @param clubId 社团ID
     * @return 申请列表
     */
    @Override
    public List<CrApplication> selectApplicationsByClubId(Long clubId)
    {
        return crApplicationMapper.selectClubApplicationList(clubId, null);
    }

    /**
     * 根据招聘ID查询申请列表
     * 
     * @param recruitmentId 招聘ID
     * @return 申请列表
     */
    @Override
    public List<CrApplication> selectApplicationsByRecruitmentId(Long recruitmentId)
    {
        return crApplicationMapper.selectApplicationListByRecruitmentId(recruitmentId);
    }

    /**
     * 根据申请状态查询申请列表
     * 
     * @param status 申请状态
     * @return 申请列表
     */
    @Override
    public List<CrApplication> selectApplicationsByStatus(String status)
    {
        CrApplication queryParam = new CrApplication();
        queryParam.setStatus(status);
        return crApplicationMapper.selectCrApplicationList(queryParam);
    }

    /**
     * 学生申请招聘职位
     * 
     * @param studentId 学生ID
     * @param recruitmentId 招聘ID
     * @param applicationContent 申请内容
     * @return 结果
     */
    @Override
    @Transactional
    public int submitApplication(Long studentId, Long recruitmentId, String applicationContent)
    {
        // 检查是否重复申请
        if (checkDuplicateApplication(studentId, recruitmentId)) {
            throw new RuntimeException("您已经申请过该职位，请勿重复申请");
        }

        // 验证申请内容
        if (StringUtils.isEmpty(applicationContent) || applicationContent.trim().length() < 10) {
            throw new RuntimeException("申请内容不能为空且不能少于10个字符");
        }

        // 获取招聘信息以获得club_id
        CrRecruitment recruitment = crRecruitmentService.selectCrRecruitmentByRecruitmentId(recruitmentId);
        if (recruitment == null) {
            throw new RuntimeException("招聘信息不存在");
        }

        // 检查招聘状态
        if (!"0".equals(recruitment.getStatus())) {
            throw new RuntimeException("该招聘已停止接受申请");
        }

        CrApplication application = new CrApplication();
        application.setUserId(studentId);
        application.setRecruitmentId(recruitmentId);
        application.setClubId(recruitment.getClubId()); // 设置club_id
        application.setApplicationContent(applicationContent);
        application.setStatus("0"); // 待审核
        application.setCreateTime(DateUtils.getNowDate());

        return crApplicationMapper.insertCrApplication(application);
    }

    /**
     * 社团审核申请
     * 
     * @param applicationId 申请ID
     * @param status 审核状态
     * @param reviewComment 审核意见
     * @param reviewScore 审核评分
     * @return 结果
     */
    @Override
    @Transactional
    public int reviewApplication(Long applicationId, String status, String reviewComment, Integer reviewScore)
    {
        CrApplication application = crApplicationMapper.selectCrApplicationByApplicationId(applicationId);
        if (application == null) {
            throw new RuntimeException("申请信息不存在");
        }

        if (!"0".equals(application.getStatus())) {
            throw new RuntimeException("只能审核待审核状态的申请");
        }

        // 验证状态值
        if (!("2".equals(status) || "3".equals(status))) {
            throw new RuntimeException("审核状态只能为通过或拒绝");
        }

        // 验证评分
        if (reviewScore != null && (reviewScore < 0 || reviewScore > 100)) {
            throw new RuntimeException("审核评分必须在0-100之间");
        }

        application.setStatus(status);
        application.setReviewResult(reviewComment);
        if (reviewScore != null) {
            application.setScore(new java.math.BigDecimal(reviewScore));
        }
        application.setReviewTime(DateUtils.getNowDate());
        application.setUpdateTime(DateUtils.getNowDate());

        return crApplicationMapper.updateCrApplication(application);
    }

    /**
     * 批量审核申请
     * 
     * @param applicationIds 申请ID数组
     * @param status 审核状态
     * @param reviewComment 审核意见
     * @return 结果
     */
    @Override
    @Transactional
    public int batchReviewApplications(Long[] applicationIds, String status, String reviewComment)
    {
        if (applicationIds == null || applicationIds.length == 0) {
            throw new RuntimeException("请选择要审核的申请");
        }

        // 验证状态值
        if (!("2".equals(status) || "3".equals(status))) {
            throw new RuntimeException("审核状态只能为通过或拒绝");
        }

        int successCount = 0;
        for (Long applicationId : applicationIds) {
            try {
                reviewApplication(applicationId, status, reviewComment, null);
                successCount++;
            } catch (Exception e) {
                // 记录错误但继续处理其他申请
                continue;
            }
        }

        return successCount;
    }

    /**
     * 撤回申请
     * 
     * @param applicationId 申请ID
     * @param studentId 学生ID
     * @return 结果
     */
    @Override
    @Transactional
    public int withdrawApplication(Long applicationId, Long studentId)
    {
        CrApplication application = crApplicationMapper.selectCrApplicationByApplicationId(applicationId);
        if (application == null) {
            throw new RuntimeException("申请信息不存在");
        }

        if (!application.getUserId().equals(studentId)) {
            throw new RuntimeException("只能撤回自己的申请");
        }

        if (!"0".equals(application.getStatus())) {
            throw new RuntimeException("只能撤回待审核状态的申请");
        }

        application.setStatus("4"); // 已取消
        application.setUpdateTime(DateUtils.getNowDate());

        return crApplicationMapper.updateCrApplication(application);
    }

    /**
     * 获取申请统计信息
     * 
     * @param recruitmentId 招聘ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getApplicationStatistics(Long recruitmentId)
    {
        Map<String, Object> statistics = new HashMap<>();
        
        // 总申请数
        CrApplication queryParam = new CrApplication();
        queryParam.setRecruitmentId(recruitmentId);
        List<CrApplication> allApplications = crApplicationMapper.selectCrApplicationList(queryParam);
        statistics.put("totalApplications", allApplications.size());

        // 按状态统计
        long pendingCount = allApplications.stream().filter(app -> "0".equals(app.getStatus())).count();
        long approvedCount = allApplications.stream().filter(app -> "2".equals(app.getStatus())).count();
        long rejectedCount = allApplications.stream().filter(app -> "3".equals(app.getStatus())).count();
        long withdrawnCount = allApplications.stream().filter(app -> "4".equals(app.getStatus())).count();

        statistics.put("pendingCount", pendingCount);
        statistics.put("approvedCount", approvedCount);
        statistics.put("rejectedCount", rejectedCount);
        statistics.put("withdrawnCount", withdrawnCount);

        // 审核通过率
        if (allApplications.size() > 0) {
            double approvalRate = (double) approvedCount / (approvedCount + rejectedCount) * 100;
            statistics.put("approvalRate", Math.round(approvalRate * 100.0) / 100.0);
        } else {
            statistics.put("approvalRate", 0.0);
        }

        return statistics;
    }

    /**
     * 获取学生申请统计
     * 
     * @param studentId 学生ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getStudentApplicationStatistics(Long studentId)
    {
        Map<String, Object> statistics = new HashMap<>();
        
        List<CrApplication> applications = crApplicationMapper.selectStudentApplicationList(studentId);
        statistics.put("totalApplications", applications.size());

        // 按状态统计
        long pendingCount = applications.stream().filter(app -> "0".equals(app.getStatus())).count();
        long approvedCount = applications.stream().filter(app -> "2".equals(app.getStatus())).count();
        long rejectedCount = applications.stream().filter(app -> "3".equals(app.getStatus())).count();
        long withdrawnCount = applications.stream().filter(app -> "4".equals(app.getStatus())).count();

        statistics.put("pendingCount", pendingCount);
        statistics.put("approvedCount", approvedCount);
        statistics.put("rejectedCount", rejectedCount);
        statistics.put("withdrawnCount", withdrawnCount);

        return statistics;
    }

    /**
     * 获取社团申请统计
     * 
     * @param clubId 社团ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getClubApplicationStatistics(Long clubId)
    {
        Map<String, Object> statistics = new HashMap<>();
        
        List<CrApplication> applications = crApplicationMapper.selectClubApplicationList(clubId, null);
        statistics.put("totalApplications", applications.size());

        // 按状态统计
        long pendingCount = applications.stream().filter(app -> "0".equals(app.getStatus())).count();
        long approvedCount = applications.stream().filter(app -> "2".equals(app.getStatus())).count();
        long rejectedCount = applications.stream().filter(app -> "3".equals(app.getStatus())).count();

        statistics.put("pendingCount", pendingCount);
        statistics.put("approvedCount", approvedCount);
        statistics.put("rejectedCount", rejectedCount);

        return statistics;
    }

    /**
     * 检查是否重复申请
     * 
     * @param studentId 学生ID
     * @param recruitmentId 招聘ID
     * @return 是否重复申请
     */
    @Override
    public boolean checkDuplicateApplication(Long studentId, Long recruitmentId)
    {
        CrApplication existingApplication = crApplicationMapper.selectApplicationByUserAndRecruitment(studentId, recruitmentId);
        
        // 检查是否有非撤回状态的申请
        return existingApplication != null && !"4".equals(existingApplication.getStatus());
    }

    /**
     * 获取待审核申请数量
     * 
     * @param clubId 社团ID
     * @return 待审核申请数量
     */
    @Override
    public long getPendingApplicationCount(Long clubId)
    {
        List<CrApplication> applications = crApplicationMapper.selectClubApplicationList(clubId, "0");
        return applications.size();
    }

    /**
     * 导出申请数据
     * 
     * @param crApplication 查询条件
     * @return 申请列表
     */
    @Override
    public List<CrApplication> exportApplications(CrApplication crApplication)
    {
        return crApplicationMapper.selectCrApplicationList(crApplication);
    }
}